// pages/fdetail/fdtail.js
const get_from = require("../../module/service.js").get_from;
const setWatcher = require("../../module/watch.js").setWatcher;
const isChanged = require("../../module/isChanged.js").isChanged;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    food_id: 0,
    food_info: {},
    attrs: [],
    is_onLoad: false,
    tempdiscount: 0,
    promotion: '',
    trolley: {
      count: 0,
      isgoods: 0,
      translist: [],
      iscpn: false
    } //购物车
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.is_onLoad = true;
    getApp().globalData.shopInfo.curr_iscpn = false;
    let food_id = parseInt(options.food_id);
    if (food_id) {
      this.data.food_id = food_id;
    }
    let translist_id = parseInt(options.translist_id);


    wx.showLoading({
      title: '正在获取数据......',
      mask: true
    });

    //获取菜品数据
    get_from("food/getFoodByFoodId", {
      food_id: food_id
    }).then((res) => {
      // this.setData({food_info: res.data});
      let food_info = res.data;

      //处理attrs
      for (let i = 0; i < food_info.attrs.length; i++) {
        let attr_val = food_info.attrs[i].attr_val;
        let tmp = {};
        let tmp_attr_val = [];
        for (let j = 0; j < attr_val.length; j++) {
          tmp = {
            name: '',
            selected: translist_id !==-1 ? getApp().globalData.shopInfo.curr_translist[translist_id].attrs[i].attr_val[j].selected : false
          };
          tmp.name = attr_val[j];
          tmp_attr_val.push(tmp);
        }
        food_info.attrs[i].attr_val = tmp_attr_val;
        tmp_attr_val = [];
      }
      console.log(food_info);
      this.setData({
        food_info: food_info
      });
      // this.data.food_info = food_info;

      //将全局数据同步过来
      let shopInfo = getApp().globalData.shopInfo;
      this.setData({
        'trolley.count': shopInfo.curr_count,
        'trolley.isgoods': shopInfo.curr_isgoods,
        'trolley.translist': shopInfo.curr_translist,
        'trolley.iscpn': shopInfo.curr_iscpn
      });
      this.data.is_onLoad = false;

      //隐藏加载提示
      wx.hideLoading();

      //注册监听器
      setWatcher(this);
    }, (err) => {
      console.log("error occured! in get_food_detail, food_id is", food_id);
      console.log("err is", err);
      wx.hideLoading();
    });

  },

  //监听数据变化
  watch: {
    trolley: {
      handler: function (val) {
        //直接将本页data里面的数据复制过去，不要使用val
        if (this.data.onLoad)
          return;
        let tmp = this.data.trolley;
        getApp().globalData.shopInfo.curr_count = tmp.count;
        getApp().globalData.shopInfo.curr_isgoods = tmp.isgoods;
        getApp().globalData.shopInfo.curr_translist = tmp.translist;
        getApp().globalData.shopInfo.curr_iscpn = tmp.iscpn;
        // console.log(getApp().globalData.shopInfo);
      },
      deep: true
    }
  },

  handleSelect(e) {
    let posx = e.currentTarget.dataset.posx;
    let posy = e.currentTarget.dataset.posy;

    //除了被选中的按钮以外的其他的selected都置为false
    let food_info = this.data.food_info;
    for (let j = 0; j < food_info.attrs[posx].attr_val.length; j++) {
      if (j == posy) {
        if (food_info.attrs[posx].attr_val[j].selected === true)
          food_info.attrs[posx].attr_val[j].selected = false;
        else
          food_info.attrs[posx].attr_val[j].selected = true;
      } else
        food_info.attrs[posx].attr_val[j].selected = false;
    }
    this.setData({
      food_info: food_info
    });
    // console.log(this.data.food_info);
  },

  //底部购物车
  //加入购物车
  addTrolley() {
    let food_info = this.data.food_info;
    let tempobj = {};
    tempobj.name = food_info.name;
    tempobj.price = food_info.price; //商品的总价格
    tempobj.shopvalue = food_info.price; //商品的单价
    tempobj.food_id = food_info.food_id;
    tempobj.number = 1;
    tempobj.attrs = food_info.attrs;

    this.seekNum(tempobj); //这里进行一步相同商品的判断
    this.setData({
      'trolley.isgoods': (food_info.price + this.data.trolley.isgoods) //商品的价格
    });
    if (this.data.trolley.isgoods > 25 && this.data.tempdiscount === 0) { //是否优惠3元
      this.setData({
        'trolley.count': this.data.trolley.count + 1, //购物车的图标
        'trolley.isgoods': (this.data.trolley.isgoods - 3), //商品的价格
        tempdiscount: 1, //只享受一次优惠
        //传给组件的商品数据
        'trolley.translist': this.data.trolley.translist,
        promotion: '满25立减3元(手机点餐专享)'
      })
    } else {
      this.setData({
        'trolley.count': this.data.trolley.count + 1, //购物车的图标
        //传给组件的商品数据
        'trolley.translist': this.data.trolley.translist
      })
    }
  },
  handleCpn() {
    this.setData({
      'trolley.iscpn': !this.data.trolley.iscpn
    });
  },
  handleDelete() {
    this.setData({
      'trolley.count': 0,
      'trolley.isgoods': 0,
      'trolley.translist': [],
      'trolley.iscpn': false
    });
  },
  handleReduce(event) {
    this.pageReduce(event.detail.cpnreduceid)
  },
  handleAdd(event) {
    this.pageAdd(event.detail.cpnaddid)
  },
  handleDefinite() {
    wx.navigateTo({
      url: '/pages/definite/definite'
    })
  },

  //一些辅助函数,判断商品重复、去掉商品和添加商品
  seekNum(obj) {
    if (this.data.trolley.translist.length !== 0) {
      const translength = this.data.trolley.translist.length;
      for (let i = 0; i < translength; ++i) {
        // console.log("translist attrs is: ");
        // console.log(this.data.trolley.translist[i].attrs);
        // console.log(", obj attrs is: ");
        // console.log(obj.attrs);
        // console.log(", their comparation is: ", !isChanged(this.data.trolley.translist[i].attrs, obj.attrs));
        // console.log(!isEqual({name: "abc"}, {name: "abc"}));
        if (this.data.trolley.translist[i].food_id === obj.food_id && !isChanged(this.data.trolley.translist[i].attrs , obj.attrs)) {
          console.log("is equal");
          this.data.trolley.translist[i].price += obj.price;
          ++this.data.trolley.translist[i].number;
          return;
        } else {
          console.log("not equal");
          // if (i === translength - 1)
            this.data.trolley.translist.push(obj);
        }
      }
    } else {
      this.data.trolley.translist.push(obj)
    }
  },

  pageReduce(tempreduceid) {
    this.data.trolley.translist[tempreduceid].number--;
    const tempvalue = this.data.trolley.translist[tempreduceid].shopvalue; //取出来要删除的商品的单价
    if (this.data.trolley.translist[tempreduceid].number === 0) {
      this.cancleArray(tempreduceid);
      this.setData({
        'trolley.translist': this.data.trolley.translist,
        'trolley.count': this.data.trolley.count - 1,
        'trolley.isgoods': this.data.trolley.isgoods - tempvalue
      });
      if (this.data.trolley.translist.length === 0) {
        this.setData({
          'trolley.iscpn': !this.data.trolley.iscpn
        });
      }
    } else {
      this.data.trolley.translist[tempreduceid].price -= this.data.trolley.translist[tempreduceid].shopvalue;
      this.setData({
        'trolley.translist': this.data.trolley.translist,
        'trolley.count': this.data.trolley.count - 1,
        'trolley.isgoods': this.data.trolley.isgoods - tempvalue
      });
    }
  },
  pageAdd(tempaddid) {
    this.data.trolley.translist[tempaddid].number++;
    this.data.trolley.translist[tempaddid].price += this.data.trolley.translist[tempaddid].shopvalue;
    this.setData({
      'trolley.translist': this.data.trolley.translist,
      'trolley.count': this.data.trolley.count + 1,
      'trolley.isgoods': this.data.trolley.isgoods + this.data.trolley.translist[tempaddid].shopvalue
    });
  },
  cancleArray(n) {
    //删除translist数组中第n项的数据
    if (n === 0) {
      this.data.trolley.translist.shift();
    } else { //删除数组中对应的元素
      this.data.trolley.translist.splice(n, 1);
    }
  }

})